import 'package:enterprise_v6_app/app/components/common/custom_no_data.dart';
import 'package:enterprise_v6_app/app/components/dialing_function.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_department_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/double_control/get_user_by_id_entity.dart';

/// 敏捷应急组织人员树
class EmergencyDepartmentTree extends StatefulWidget {
  const EmergencyDepartmentTree({required this.businessId, super.key});

  /// 预案id
  final String businessId;

  @override
  State<EmergencyDepartmentTree> createState() => _EmergencyDepartmentTreeState();
}

class _EmergencyDepartmentTreeState extends State<EmergencyDepartmentTree> {
  List<EmergencyDepartmentEntity> departmentTreeList = [];

  @override
  void initState() {
    super.initState();
    _getDepartmentTree();
  }

  /// 获取组织人员树
  Future<void> _getDepartmentTree() async {
    //获取所有组织数据
    final res = await HttpUtil().generateGetRequest<List<EmergencyDepartmentEntity>>(
      Interface.getEmeDepartmentTree,
      queryParameters: {'businessId': widget.businessId},
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        departmentTreeList = result.data!;
      }
      setState(() {});
    });
  }

  /// 点击组织节点
  Future<void> clickOnNode(EmergencyDepartmentEntity treeEntity) async {
    treeEntity.isExpand = !treeEntity.isExpand;
    // 展开状态且节点人员为空调用接口查询人员
    if (treeEntity.isExpand && treeEntity.userList.isEmpty) {
      final userList = await getUserByDepartment(treeEntity.id);
      if (userList.isNotEmpty) {
        // 人员id集合
        final List<String> userIds = userList.map((e) => e.userId!).toList();
        // 获取人员详情
        final List<GetUserByIdEntity> userDetailList = await getUserByIds(userIds);
        treeEntity.userList.addAll(userDetailList);
      }
      setState(() {});
    } else {
      setState(() {});
    }
  }

  /// 通过部门查询人员
  Future<List<GetUserByIdEntity>> getUserByDepartment(String departmentId) async {
    final List<GetUserByIdEntity> userList = [];
    //获取组织人员数据
    final res = await HttpUtil().generateGetRequest<List<GetUserByIdEntity>>(
      Interface.getUserByDepartment,
      queryParameters: {
        'departmentId': departmentId,
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        userList.addAll(result.data!);
      }
    });
    return userList;
  }

  /// 获取组织人员详情信息
  Future<List<GetUserByIdEntity>> getUserByIds(List<String> userIdList) async {
    final List<GetUserByIdEntity> userList = [];
    //获取组织人员数据
    final res = await HttpUtil()
        .generatePostRequest<List<GetUserByIdEntity>>(
          Interface.getUserByIds,
          data: userIdList,
        )
        .execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        userList.addAll(result.data!);
      }
    });
    return userList;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        alignment: Alignment.topCenter,
        color: const Color(0xffffffff),
        child: departmentTreeList.isEmpty
            ? const CustomNoData()
            : SingleChildScrollView(
                child: Column(
                children: departmentTreeList.map((item) {
                  return _getTreeView(item, 0);
                }).toList(),
              )));
  }

  /// 部门数据每一项的显示
  /// [treeEntity] 当前节点数据
  /// [level] 所在层级
  Widget _getTreeView(EmergencyDepartmentEntity treeEntity, int level) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          constraints: BoxConstraints(
            minHeight: 55.w,
          ),
          padding: EdgeInsets.symmetric(vertical: 10.w),
          child: Row(
            children: [
              // 间距
              SizedBox(width: 20.w * level),
              SizedBox(
                width: 40.w,
                child: SvgPicture.asset(
                  treeEntity.isExpand ? AppImages.icon_arrow_drop : AppImages.icon_arrow_right,
                  width: 12.w,
                  height: 12.w,
                ),
              ),
              Expanded(
                child: Text(
                  treeEntity.function,
                  style: TextStyle(
                    fontSize: 15.sp,
                    fontWeight: FontWeight.w500,
                    color: const Color(0xff333333),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 10.w),
                child: Text(
                  '|',
                  style: TextStyle(
                    fontSize: 15.sp,
                    fontWeight: FontWeight.w500,
                    color: const Color(0xffDDE6F0),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 20.w),
                child: Text(
                  '职责',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                    color: const Color(0xff417EFB),
                  ),
                ),
              ).clickOnce(() {
                // 显示选择类型的编辑弹框
                Get.dialog(_getResponsibilityView(treeEntity.emergencyDescribe));
              })
            ],
          ),
        ).clickOnce(() {
          clickOnNode(treeEntity);
        }),
        Divider(
          height: 0.1.w,
          color: const Color(0xffDDE6F0),
        ),
        AnimatedSize(
          duration: const Duration(milliseconds: 500),
          // curve: Curves.easeInExpo,
          curve: Curves.easeInOutExpo,
          child: SizedBox(
            height: treeEntity.isExpand ? null : 0,
            child: Column(
              children: [
                // 组织部门
                ...treeEntity.children.map((item) {
                  return _getTreeView(item, level + 1);
                }),
                // 人员
                ...treeEntity.userList.map((item) {
                  return _getUserTreeView(item, level + 1);
                })
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 部门下人员信息
  /// [userEntity] 人员数据
  /// [level] 所在层级
  Widget _getUserTreeView(GetUserByIdEntity userEntity, int level) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          constraints: BoxConstraints(
            minHeight: 55.w,
          ),
          padding: EdgeInsets.symmetric(vertical: 10.w),
          child: Row(
            children: [
              // 间距
              SizedBox(width: 20.w * level),
              // 占位
              SizedBox(width: 40.w),
              Expanded(
                child: Text(
                  '${userEntity.getShowName()}\n${userEntity.mobile}',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w400,
                    color: const Color(0xff333333).withOpacity(0.5),
                  ),
                ).clickOnce(() {
                  if (userEntity.mobile!.isNotEmpty) {
                    DialingFunction.selectDialingBottomSheet(dataList: [userEntity.mobile!]);
                  }
                }),
              ),
            ],
          ),
        ),
        Divider(
          height: 0.1.w,
          color: const Color(0xffECECEC),
        ),
      ],
    );
  }

  /// 职责弹窗
  Widget _getResponsibilityView(String value) {
    return Container(
      alignment: Alignment.center,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        width: 300.w,
        height: 374.w,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(20.w)),
          gradient: const LinearGradient(
              //渐变位置
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              //渐变颜色[始点颜色, 结束颜色]
              colors: [
                Color(0xffE7EAFF),
                Color(0xffffffff),
                Color(0xffffffff),
                Color(0xffffffff),
              ]),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.symmetric(vertical: 20.w),
              alignment: Alignment.center,
              child: Text(
                '职责',
                style: TextStyle(color: Colors.black, fontSize: 18.sp, fontWeight: FontWeight.w500),
              ),
            ),
            Expanded(
              child: Container(
                alignment: Alignment.topLeft,
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 9.w),
                decoration: BoxDecoration(
                    color: const Color(0xffF7F7FB),
                    border: Border.all(color: const Color(0xffEBEDF0), width: 1.w),
                    borderRadius: BorderRadius.all(Radius.circular(8.r))),
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      Text(
                        value,
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 13.sp,
                          fontWeight: FontWeight.w400,
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.symmetric(vertical: 25.w),
              width: 270.w,
              height: 40.w,
              child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(const Color(0xff5C6DFF)),
                ),
                onPressed: Get.back,
                child: Text(
                  '确定',
                  style: TextStyle(fontSize: 16.sp, color: Colors.white),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
